package com.runchamp;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;


@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class CreateRace extends Activity { //use to be: ActionMenuView.OnMenuItemClickListener. maybe use in the future
    private Intent intent;
    private TextView tagsTextView;
    private ToggleButton privacyButton;
    private PopupMenu distanceMenu;
    private Spinner spinnerDist, spinnerDuration;
    private Calendar calDate;
    private Calendar calTime;
    private Calendar tempDate;
    private TextView etTime;
    private TextView etDate;
    private int hours;
    private int min;
    private int day;
    private int month;
    private int year;
    private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            int hour;
            String am_pm;
            if (hourOfDay > 12) {
                hour = hourOfDay - 12;
                am_pm = "PM";
            } else {
                hour = hourOfDay;
                am_pm = "AM";
            }

            int tempHours = hourOfDay;
            int TempMin = minute;

            //check legal
            tempDate = Calendar.getInstance();
            tempDate.set(Calendar.YEAR, year);
            tempDate.set(Calendar.MONTH, month - 1);
            tempDate.set(Calendar.DAY_OF_MONTH, day);
            tempDate.set(Calendar.HOUR_OF_DAY, tempHours);
            tempDate.set(Calendar.MINUTE, TempMin);

            //legal:
            if (tempDate.after(calDate)) {
                hours = tempHours;
                min = TempMin;
                String min0 = "";
                if (min < 10) {
                    min0 = "0";
                }
                String hour0 = "";
                if (hour < 10) {
                    hour0 = "0";
                }
                etTime.setText(hour0 + String.valueOf(hour) + " : " + min0 + String.valueOf(min) + " " + am_pm);
            } else {
                Toast.makeText(getApplicationContext(), "Illegal Time! please select future time", Toast.LENGTH_LONG).show();
            }
        }
    };
    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            int tempDay = selectedDay;
            int tempMonth = selectedMonth + 1;
            int tempYear = selectedYear;

            //check legal
            tempDate = Calendar.getInstance();
            tempDate.set(Calendar.YEAR, tempYear);
            tempDate.set(Calendar.MONTH, tempMonth - 1);
            tempDate.set(Calendar.DAY_OF_MONTH, tempDay);
            tempDate.set(Calendar.HOUR_OF_DAY, hours);
            tempDate.set(Calendar.MINUTE, min);

            //legal:
            if (tempDate.after(calDate)) {
                etDate.setText(selectedDay + "/" + (tempMonth) + "/" + selectedYear);
                day = tempDay;
                month = tempMonth;
                year = tempYear;
            }
            //illegal
            else {
                Toast.makeText(getApplicationContext(), "Illegal Date! please select future date", Toast.LENGTH_LONG).show();
            }

        }
    };
    private String user;
    private Intent raceInfoIntent;
    private ArrayList<String> arrayList1, arrayList2;
    private ArrayAdapter<String> adp, adp2;
    private Boolean exposeAdvance;
    private ImageButton arrowButton;
    private LinearLayout durationLine;
    private LinearLayout privacyLine;
    private LinearLayout tagLine;
    /*initialize with defauls value*/
    private String distance = "5";
    private String estimatedTime = "30.0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_race);
        intent = new Intent(this, ChooseRace.class);
        tagsTextView = (TextView) findViewById(R.id.tagsWritten);
        privacyButton = (ToggleButton) findViewById(R.id.PrivacyButton);

        //advance Exposure
        arrowButton = (ImageButton) findViewById(R.id.arrowButton);
        durationLine = (LinearLayout) findViewById(R.id.lineDuration);
        privacyLine = (LinearLayout) findViewById(R.id.linePrivacy);
        tagLine = (LinearLayout) findViewById(R.id.lineTags);
        exposeAdvance = false;
        arrowButton.setImageResource(R.drawable.ic_arror_down);
        durationLine.setVisibility(View.GONE);
        privacyLine.setVisibility(View.GONE);
        tagLine.setVisibility(View.GONE);
        spinnerDist = (Spinner) findViewById(R.id.spinnerDist);
        spinnerDuration = (Spinner) findViewById(R.id.spinnerEstimated);
        raceInfoIntent = new Intent(this, RaceInfo.class);
        arrayList1 = new ArrayList<String>();
        arrayList2 = new ArrayList<String>();

        adp = new ArrayAdapter<String>(this, R.layout.spinnertemp, arrayList1);
        adp2 = new ArrayAdapter<String>(this, R.layout.spinnertemp, arrayList2);

        /*distance spinner settings*/
        spinnerDist.setAdapter(adp2);
        arrayList2.add("100 M");
        arrayList2.add("200 M");
        arrayList2.add("500 M");
        arrayList2.add("1 KM");
        arrayList2.add("2 KM");
        arrayList2.add("3 KM");
        arrayList2.add("4 KM");
        arrayList2.add("5 KM");
        arrayList2.add("6 KM");
        arrayList2.add("8 KM");
        arrayList2.add("10 KM");
        adp2.notifyDataSetChanged();
        arrayList1.clear();

        /*duration pace spinner settings*/
        spinnerDuration.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        estimatedTime = String.format("%.1f", 3.0 * Float.parseFloat(distance));
                        break;
                    case 1:
                        estimatedTime = String.format("%.1f", 3.5 * Float.parseFloat(distance));
                        break;
                    case 2:
                        estimatedTime = String.format("%.1f", 4.0 * Float.parseFloat(distance));
                        break;
                    case 3:
                        estimatedTime = String.format("%.1f", 4.5 * Float.parseFloat(distance));
                        break;
                    case 4:
                        estimatedTime = String.format("%.1f", 5.0 * Float.parseFloat(distance));
                        break;
                    case 5:
                        estimatedTime = String.format("%.1f", 5.5 * Float.parseFloat(distance));
                        break;
                    case 6:
                        estimatedTime = String.format("%.1f", 6.0 * Float.parseFloat(distance));
                        break;
                    case 7:
                        estimatedTime = String.format("%.1f", 6.5 * Float.parseFloat(distance));
                        break;
                    case 8:
                        estimatedTime = String.format("%.1f", 7.0 * Float.parseFloat(distance));
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /*destination spinner listener settings*/
        spinnerDist.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        distance = "0.1";
                        break;
                    case 1:
                        distance = "0.2";
                        break;
                    case 2:
                        distance = "0.5";
                        break;
                    case 3:
                        distance = "1";
                        break;
                    case 4:
                        distance = "2";
                        break;
                    case 5:
                        distance = "3";
                        break;
                    case 6:
                        distance = "4";
                        break;
                    case 7:
                        distance = "5";
                        break;
                    case 8:
                        distance = "6";
                        break;
                    case 9:
                        distance = "8";
                        break;
                    case 10:
                        distance = "10";
                        break;
                }
                estimatedTime = String.format("%.1f", 6.0 * Float.parseFloat(distance));
                spinnerDuration.setAdapter(adp);
                arrayList1.clear();
                arrayList1.add(String.format("3 min/KM"));
                arrayList1.add(String.format("3.5 min/KM"));
                arrayList1.add(String.format("4 min/KM"));
                arrayList1.add(String.format("4.5 min/KM"));
                arrayList1.add(String.format("5 min/KM"));
                arrayList1.add(String.format("5.5 min/KM"));
                arrayList1.add(String.format("6 min/KM"));
                arrayList1.add(String.format("6.5 min/KM"));
                arrayList1.add(String.format("7 min/KM"));
                adp.notifyDataSetChanged();
                spinnerDuration.setSelection(6);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerDuration.setSelection(6);
        spinnerDist.setSelection(7);

        /*date and time settings*/
        calTime = Calendar.getInstance();
        calTime.add(Calendar.MINUTE, 1);
        hours = calTime.get(Calendar.HOUR_OF_DAY);
        min = calTime.get(Calendar.MINUTE);
        etTime = (TextView) findViewById(R.id.timeDisplay);
        String am_pm;
        int hour;
        if (hours > 12) {
            hour = hours - 12;
            am_pm = "PM";
        } else {
            hour = hours;
            am_pm = "AM";
        }
        String min0 = "";
        if (min < 10) {
            min0 = "0";
        }
        String hour0 = "";
        if (hour < 10) {
            hour0 = "0";
        }

        /*time dialog display settings*/
        etTime.setText(hour0 + String.valueOf(hour) + " : " + min0 + String.valueOf(min) + " " + am_pm);
        etTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(0);
            }
        });

        /*calendar dialog display settings*/
        calDate = Calendar.getInstance();
        day = calDate.get(Calendar.DAY_OF_MONTH);
        month = calDate.get(Calendar.MONTH);
        month++;
        year = calDate.get(Calendar.YEAR);
        etDate = (TextView) findViewById(R.id.dateDisplay);
        etDate.setText(day + "/" + (month) + "/" + year);
        etDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(1);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_create_race, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void createRace(View v) {
        String privacy = ((privacyButton.isChecked()) ? "Public" : "Private");
        String estimatedTimeLocal = estimatedTime;
        String hourLocal = hours + ":" + min;
        String distanceLocal = distance;
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = prefs.getString("userID", "");
        AsyncHttpClient client = new AsyncHttpClient();
        String tagsString = tagsTextView.getText().toString().equals("") ? "RunForever" : tagsTextView.getText().toString();
        String path = String.format("http://runtobo.appspot.com/racesManager/newRace?tags=%s&estimated=%s&privacy=%s&manager=%s&distance=%s&year=%s&month=%s&day=%s&hour=%s",
                tagsString, estimatedTimeLocal, privacy, user, distanceLocal, year, month, day, hourLocal);
        client.get(path,
                new JsonHttpResponseHandler() {

                    public void onSuccess(JSONArray response) {
                        try {
                            JSONObject race = response.getJSONObject(0);
                            String Key = race.get("raceID").toString();
                            String Name = race.get("Manager").toString();
                            String RaceDistance = race.get("Distance").toString();
                            String Time = race.get("Time").toString();
                            String Manager = race.get("Manager").toString();
                            String ManagerId = race.get("ManagerId").toString();
                            String Participants = race.get("Participants").toString();
                            String Tags = race.get("Tags").toString();
                            String Estimated = race.get("Estimated").toString();
                            Bundle raceBundle = new Bundle();
                            raceBundle.putString("Key", Key);
                            raceBundle.putString("Name", Name);
                            raceBundle.putString("Distance", RaceDistance);
                            raceBundle.putString("Time", Time);
                            raceBundle.putString("Manager", Manager);
                            raceBundle.putString("ManagerId", ManagerId);
                            raceBundle.putString("Participants", Participants);
                            raceBundle.putString("Tags", Tags);
                            raceBundle.putString("Estimated", Estimated);

                            raceInfoIntent.putExtras(raceBundle);
                            startActivity(raceInfoIntent);
                            finish();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {

                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        tagsTextView.setText("errorrr");
                    }
                });

    }

    //@Override
    public void onClick(View v) {
        distanceMenu.show();
    }

    public void changeAdvanceExposure(View v) {
        if (exposeAdvance) {
            exposeAdvance = false;
            arrowButton.setImageResource(R.drawable.ic_arror_down);
            durationLine.setVisibility(View.GONE);
            privacyLine.setVisibility(View.GONE);
            tagLine.setVisibility(View.GONE);

        } else {
            exposeAdvance = true;
            arrowButton.setImageResource(R.drawable.ic_arrow_up);
            durationLine.setVisibility(View.VISIBLE);
            privacyLine.setVisibility(View.VISIBLE);
            tagLine.setVisibility(View.VISIBLE);
        }
    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        if (id == 0)
            return new TimePickerDialog(this, timePickerListener, hours, min, false);
        else
            return new DatePickerDialog(this, datePickerListener, year, month - 1, day);
    }

}
